package com.zhixiang.core.util;

import org.apache.commons.lang.StringUtils;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.SQLQuery;
import org.hibernate.SessionFactory;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.id.Configurable;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.type.Type;

import javax.persistence.Column;
import javax.persistence.Table;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.Properties;

/**
 * oracle自增生成器
 * @author whw
 * @version v1.0
 * @date 2016/12/21
 */
public class IdGenerator implements Configurable,IdentifierGenerator {
//    private String pk;

    @Override
    public void configure(Type type, Properties properties, Dialect dialect) throws MappingException {
//        this.pk = String.valueOf(properties.get("pk"));
    }

    @Override
    public Serializable generate(SessionImplementor sessionImplementor, Object o) throws HibernateException {
        try {
            String tableName = o.getClass().getAnnotation(Table.class).name();
            Long nextId = 0L;
            String[] idNames = ReflectUtils.getIdNames(o);
            if(null != idNames && idNames.length > 0) {
                String idName = idNames[0];
                //add by gt
                Field field = ReflectUtils.getDeclaredField(o, idName);
                if(field!=null&&field.isAnnotationPresent(Column.class)){
                    String name = field.getAnnotation(Column.class).name();
                    if(StringUtils.isNotEmpty(name)){
                        idName = name;
                    }
                }
                String sql = "select max(" + idName + ") from " + tableName;
                SessionFactory sessionFactory = WebUtils.getBean(SessionFactory.class, "sessionFactory");
                //当对一个表插入多条数据时，强制把最大ID刷新到数据库缓存中，并不是数据库日志提交
                sessionFactory.getCurrentSession().flush();
                SQLQuery sqlQuery = sessionFactory.getCurrentSession().createSQLQuery(sql);
                Object obj = sqlQuery.uniqueResult();
                if (obj != null) {
                    nextId = Long.parseLong(String.valueOf(obj));
                }
                nextId += 1;
                System.out.println(nextId);
                return nextId;
            }else{
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) throws ClassNotFoundException {
        System.out.println(StringUtils.lowerCase("ABC"));

        Class c = Class.forName("com.zhixiang.xaec.service.system.SerialNumberService");
        System.out.println(c);
    }
}
